package com.example.tourpal;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tourpal.model.Comment;
import com.example.tourpal.model.Consume;
import com.example.tourpal.model.Journey;
import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.CommentLishenter;
import com.example.tourpal.model.LocalDataLoader.JourneyLishenter;
import com.example.tourpal.model.LocalDataLoaderHelp;
import com.example.tourpal.model.Page;
import com.example.tourpal.model.Plan;
import com.example.tourpal.model.User;
import com.example.tourpal.user.RoundImageView;
import com.example.tourpal.widget.CustomPagerAdapter;
import com.example.tourpal.widget.CustomViewPager;

public class PlanOverViewActivity extends Activity {

	private static final String UNDER_LINE = "-";
	public static final int RESULT_BACK = 0;

	// UI
	private ImageView backBt;
	private TextView planName;
	private TextView planDate;

	private LinearLayout spotGallery;

	private TextView planSpotName;
	private TextView planSpotDate;
	private TextView planSpotFollowContent;
	private ImageView planSpotFollowBt;
	private LinearLayout spotOverView;
	private ImageView replyBt;
	private LinearLayout messageContent;

	private LinearLayout inputBar;
	private EditText input;
	private ImageButton sendBt;

	private ImageButton spotShareBt;
	private ImageButton spotFollowBt;

	private Context context;
	private Intent planIntent;
	private InputMethodManager imm;

	// Data
	private ViewGroup root;
	private User user;
	private int journeyId;
	private int planUserId;
	private Journey tempJ;
	private List<Plan> planDetial;
	private String spotNameList;

	private SimpleDateFormat sFormat;
	private SimpleDateFormat tFormat;

	private boolean isPublic;
	private boolean isFollow = false;

	private ArrayList<View> pageViews;

	private ViewGroup rootGroup;
	private CustomViewPager viewPaper;
	private int currentPage = 0;

	private ArrayList<Integer> spotIDList;

	protected LayoutInflater mInflater;
	protected ShareTask shareTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;

		sFormat = new SimpleDateFormat(getText(R.string.date_format_1)
				.toString(), Locale.getDefault());
		tFormat = new SimpleDateFormat(getText(R.string.date_format_2)
				.toString(), Locale.getDefault());

		setContentView(R.layout.plan_details_viewpage);

		planIntent = getIntent();
		user = (User) planIntent.getSerializableExtra("user");
		planUserId = planIntent.getIntExtra("planUserId", 0);

		backBt = (ImageView) findViewById(R.id.back);
		planName = (TextView) findViewById(R.id.planName);
		planDate = (TextView) findViewById(R.id.planDate);

		spotGallery = (LinearLayout) findViewById(R.id.spotGallery);

		viewPaper = (CustomViewPager) findViewById(R.id.spotPager);

		inputBar = (LinearLayout) findViewById(R.id.inputBar);
		input = (EditText) findViewById(R.id.input);
		sendBt = (ImageButton) findViewById(R.id.send);

		spotShareBt = (ImageButton) findViewById(R.id.spotShare);
		spotFollowBt = (ImageButton) findViewById(R.id.spotFollow);

		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		spotNameList = "";

		setupPlanView();
	}

	private void setupPlanView() {

		planName.setText(planIntent.getStringExtra("planName"));
		planDate.setText(planIntent.getStringExtra("planDate"));

		spotIDList = new ArrayList<Integer>();

		backBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		sendBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (replyBt.getVisibility() == View.INVISIBLE) {

					// >>>post service
					postComment(user, input.getText().toString());
					Toast.makeText(context, "Post Service!!!",
							Toast.LENGTH_SHORT).show();

					replyBt.setVisibility(View.VISIBLE);
					inputBar.setVisibility(View.GONE);
					input.getText().clear();
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

				}
			}
		});

		int planID = planIntent.getIntExtra("planID", 1);
		if (planID == -1) {
			fillPlan((Journey) planIntent.getSerializableExtra("journeyItem"));
		} else {
			requestPlanData(planID);
		}

		spotShareBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (shareTask != null) {
					if (!shareTask.isCancelled()) {
						shareTask.cancel(true);
					}

					shareTask = null;
				}
				shareTask = new ShareTask();
				shareTask.execute("0");
			}
		});

		spotFollowBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(context, FollowSelectActivity.class);
				intent.putExtra("spotNameList", spotNameList);
				intent.putExtra("user", user);
				intent.putExtra("planUserId", planUserId);
				startActivity(intent);

				overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
			}
		});
	}

	private class ShareTask extends AsyncTask<String, Integer, String> {

		LayoutInflater layoutInflater = LayoutInflater.from(context);
		LinearLayout shareTemplet = (LinearLayout) layoutInflater.inflate(
				R.layout.share_templet, root);

		@Override
		protected String doInBackground(String... params) {
			int index = Integer.valueOf(params[0]);

			if (index > 0) {

			} else {
				LinearLayout shareTempletTitle = new LinearLayout(context);
				LinearLayout.LayoutParams rParams = new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				shareTempletTitle.setLayoutParams(rParams);
				shareTempletTitle.setPadding(16, 16, 16, 16);
				shareTempletTitle.setOrientation(LinearLayout.VERTICAL);
				shareTempletTitle.setGravity(Gravity.CENTER);
				shareTempletTitle.setBackgroundColor(0xff2ba47b);

				if (user != null) {
					RoundImageView head = new RoundImageView(context);
					head.setImageResource(getRandomPersonHeadRes());
					shareTempletTitle.addView(head,
							new LinearLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT));
				}

				TextView planName = new TextView(context);
				planName.setTextColor(Color.WHITE);
				planName.setTextSize(24);
				planName.setText(tempJ.getName());
				planName.setGravity(Gravity.CENTER_VERTICAL);

				shareTempletTitle.addView(planName,
						new LinearLayout.LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT));
				shareTemplet.addView(shareTempletTitle);

				for (int i = 0; i < tempJ.getPlans().size(); i++) {
					LinearLayout shareTempletItem = new LinearLayout(context);
					LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT);
					lParams.setMargins(0, 16, 0, 16);
					shareTempletItem.setLayoutParams(lParams);
					Random rnd = new Random();
					switch (rnd.nextInt(4)) {
					case 0:
						shareTempletItem
								.setBackgroundResource(R.drawable.share_template_item_1);
						break;
					case 1:
						shareTempletItem
								.setBackgroundResource(R.drawable.share_template_item_2);
						break;
					case 2:
						shareTempletItem
								.setBackgroundResource(R.drawable.share_template_item_3);
						break;
					case 3:
						shareTempletItem
								.setBackgroundResource(R.drawable.share_template_item_4);
						break;
					default:
						shareTempletItem
								.setBackgroundResource(R.drawable.share_template_item_1);
						break;
					}
					shareTempletItem.setOrientation(LinearLayout.VERTICAL);
					shareTempletItem.setPadding(48, 16, 16, 16);

					Plan tempP = tempJ.getPlans().get(i);

					TextView spotName = new TextView(context);
					spotName.setTextColor(Color.WHITE);
					spotName.setText(tempP.getName());
					spotName.setTextSize(20);
					spotName.setGravity(Gravity.END);

					shareTempletItem.addView(spotName);

					TextView spotDate = new TextView(context);
					spotDate.setTextColor(Color.WHITE);
					spotDate.setText(tempP.getStartTime() + UNDER_LINE
							+ tempP.getEndTime());
					spotDate.setTextSize(12);
					spotDate.setGravity(Gravity.END);

					shareTempletItem.addView(spotDate);

					for (int j = 0; j < tempP.getConsumes().size(); j++) {
						Consume tempC = tempP.getConsumes().get(j);
						TextView spotConsume = new TextView(context);
						spotConsume.setText("    " + tempC.getDescription());
						spotConsume.setWidth(360);
						spotConsume.setTextColor(Color.WHITE);

						int childIcon = R.drawable.share_other_small;
						int type = tempC.getType();
						switch (type) {
						case 1:
							childIcon = R.drawable.share_food_small;
							break;
						case 2:
							childIcon = R.drawable.share_live_small;
							break;
						case 3:
							childIcon = R.drawable.share_go_small;
							break;
						case 4:
							childIcon = R.drawable.share_swim_small;
							break;
						case 5:
							childIcon = R.drawable.share_amuse_small;
							break;
						case 6:
							childIcon = R.drawable.share_buy_small;
							break;

						default:
							break;
						}
						Drawable childD = getResources().getDrawable(childIcon);
						childD.setBounds(0, 0, childD.getMinimumWidth(),
								childD.getMinimumHeight());
						spotConsume.setCompoundDrawables(childD, null, null,
								null);
						LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT);
						lp.setMargins(0, 16, 0, 16);
						shareTempletItem.addView(spotConsume, lp);
					}

					String description = tempP.getDescription();
					if (!description.isEmpty()) {
						TextView spotFollow = new TextView(context);
						spotFollow.setTextColor(Color.WHITE);
						spotFollow.setText(description);
						spotFollow.setWidth(360);
						spotFollow.setBackgroundColor(0x44000000);
						spotFollow.setTextSize(18);

						shareTempletItem.addView(spotFollow);
					}

					shareTemplet.addView(shareTempletItem);
				}
			}

			shareTemplet.measure(
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			shareTemplet.layout(0, 0, shareTemplet.getMeasuredWidth(),
					shareTemplet.getMeasuredHeight());

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			Bitmap bitmap = Bitmap.createBitmap(shareTemplet.getWidth(),
					shareTemplet.getHeight(), Bitmap.Config.ARGB_8888);

			shareTemplet.draw(new Canvas(bitmap));

			if (bitmap == null) {
				Toast.makeText(context, "bitmap == null", Toast.LENGTH_SHORT)
						.show();
				return;
			}

			try {
				FileOutputStream fos = new FileOutputStream(
						"storage/sdcard0/Pictures/planCard.jpg");

				bitmap.compress(CompressFormat.JPEG, 100, fos);

				fos.close();

				Toast.makeText(context, "creat file success.",
						Toast.LENGTH_SHORT).show();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Intent intent = new Intent();
			intent.setClass(context, ShareAppActivity.class);
			startActivity(intent);

			overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);

			cancel(true);

			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	protected void postComment(User user, String commentText) {

		Date now = new Date();
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,
				DateFormat.SHORT);

		final Comment comment = new Comment(df.format(now),
				spotIDList.get(currentPage), commentText, user.getId(),
				user.getUserName());

		LocalDataLoader loader = new LocalDataLoader(context);
		loader.publishComment(comment, journeyId, new CommentLishenter() {

			@Override
			public void requestCommentList(List<Comment> comments, Page page) {
				// TODO Auto-generated method stub

			}

			@Override
			public void publishCommentDone(int resultCode) {
				if (resultCode == LocalDataLoaderHelp.PUBLISH_COMMENT_DONE_ACTION) {
					Toast.makeText(context, "Comment done.", Toast.LENGTH_SHORT)
							.show();
					addComment(currentPage, comment);
				} else {
					Toast.makeText(context, "Comment fail!", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});

	}

	private void fillSpotDetails(int spotID) {
		View spotPage = mInflater
				.inflate(R.layout.spot_details_page, rootGroup);
		pageViews.add(spotPage);

		planSpotName = (TextView) spotPage.findViewById(R.id.planSpotName);
		planSpotName.setText(planDetial.get(spotID).getName());

		planSpotDate = (TextView) spotPage.findViewById(R.id.planSpotDate);

		planSpotFollowContent = (TextView) spotPage
				.findViewById(R.id.followContent);
		planSpotFollowBt = (ImageView) spotPage.findViewById(R.id.spotFollow);
		spotOverView = (LinearLayout) spotPage.findViewById(R.id.spotOverView);

		replyBt = (ImageView) spotPage.findViewById(R.id.reply);
		replyBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (inputBar.getVisibility() == View.GONE) {
					inputBar.setVisibility(View.VISIBLE);
					input.requestFocus();
					replyBt.setVisibility(View.INVISIBLE);
					imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
				}
			}
		});

		if (user != null && user.getId() != planUserId) {
			replyBt.setVisibility(View.VISIBLE);
		} else {
			replyBt.setVisibility(View.INVISIBLE);
		}

		messageContent = (LinearLayout) spotPage
				.findViewById(R.id.messageContent);

		isPublic = planDetial.get(spotID).getIspublic() == 1 ? true : false;
		if (isPublic) {

			planSpotFollowContent.setVisibility(View.VISIBLE);
			planSpotFollowContent.setText(planDetial.get(spotID)
					.getDescription());
			if (user != null && user.getId() != planUserId) {
				planSpotFollowBt.setVisibility(View.VISIBLE);
			} else {
				planSpotFollowBt.setVisibility(View.GONE);
			}

			spotNameList += planSpotName.getText() + UNDER_LINE;
		} else {
			planSpotFollowContent.setVisibility(View.GONE);
			planSpotFollowBt.setVisibility(View.GONE);
		}

		List<Consume> consumeDetial = planDetial.get(spotID).getConsumes();
		List<Comment> commentDetial = planDetial.get(spotID).getPlanComments();

		try {
			planSpotDate.setText(tFormat.format(sFormat.parse(planDetial.get(
					spotID).getStartTime())));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		fillSpotList(consumeDetial);
		fillMessageList(spotID, commentDetial);

	}

	private void fillSpotList(List<Consume> consumeDetial) {
		LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		childParams.setMargins(0, 0, 0, 28);
		if (spotOverView.getChildCount() > 2) {
			spotOverView.removeViews(0, spotOverView.getChildCount() - 2);
		}

		for (int i = 0; i < consumeDetial.size(); i++) {
			TextView child = new TextView(this);
			child.setText("    " + consumeDetial.get(i).getDescription());
			child.setTextSize(16);
			child.setTextColor(0xff666666);

			int childIcon = R.drawable.other_small;
			int type = consumeDetial.get(i).getType();
			switch (type) {
			case 1:
				childIcon = R.drawable.food_small;
				break;
			case 2:
				childIcon = R.drawable.live_small;
				break;
			case 3:
				childIcon = R.drawable.go_small;
				break;
			case 4:
				childIcon = R.drawable.swim_small;
				break;
			case 5:
				childIcon = R.drawable.amuse_small;
				break;
			case 6:
				childIcon = R.drawable.buy_small;
				break;

			default:
				break;
			}
			Drawable childD = getResources().getDrawable(childIcon);
			childD.setBounds(0, 0, childD.getMinimumWidth(),
					childD.getMinimumHeight());
			child.setCompoundDrawables(childD, null, null, null);
			spotOverView.addView(child, i, childParams);
		}
	}

	private void fillMessageList(int pageIndex, List<Comment> commentDetial) {

		for (int i = 0; i < commentDetial.size(); i++) {

			addComment(pageIndex, commentDetial.get(i));

		}

	}

	private void addComment(int pageIndex, Comment comment) {
		LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

		LinearLayout child = new LinearLayout(this);
		child.setOrientation(LinearLayout.VERTICAL);
		child.setPadding(0, 0, 0, 10);

		TextView childMsg = new TextView(this);
		childMsg.setText(comment.getUserNikeName() + ":"
				+ comment.getPlanComment());
		childMsg.setTextColor(Color.GRAY);

		TextView childTime = new TextView(this);
		childTime.setGravity(Gravity.END);
		childTime.setText(comment.getCreateTime());
		childTime.setTextColor(Color.GRAY);

		child.addView(childMsg);
		child.addView(childTime);

		messageContent = (LinearLayout) pageViews.get(pageIndex).findViewById(
				R.id.messageContent);
		messageContent.addView(child, childParams);

		if (messageContent.getChildCount() == 0) {
			messageContent.setVisibility(View.GONE);
		} else {
			messageContent.setVisibility(View.VISIBLE);
		}
	}

	private void requestPlanData(int journeyId) {

		this.journeyId = journeyId;

		pageViews = new ArrayList<View>();

		planDetial = new ArrayList<Plan>();

		LocalDataLoader loader = new LocalDataLoader(context);
		loader.startLoadJourneyData(journeyId, new JourneyLishenter() {

			@Override
			public void requestJourneyList(Journey journey) {
				if (journey == null) {
					return;
				}
				tempJ = journey;
				fillPlan(tempJ);
			}

		});

	}

	private void fillPlan(Journey journey) {
		planDetial = journey.getPlans();

		mInflater = getLayoutInflater();

		LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		childParams.setMargins(3, 0, 4, 0);
		for (int i = 0; i < planDetial.size(); i++) {
			spotIDList.add(planDetial.get(i).getId());

			ImageView galleryItem = new ImageView(context);
			if (i == 0) {
				galleryItem
						.setBackgroundResource(R.drawable.page_indicator_sel);
			} else {
				galleryItem.setBackgroundResource(R.drawable.page_indicator_no);
			}
			spotGallery.addView(galleryItem, childParams);

			fillSpotDetails(i);
		}

		viewPaper.setAdapter(new CustomPagerAdapter(pageViews));
		viewPaper.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				for (int i = 0; i < spotGallery.getChildCount(); i++) {
					ImageView galleryItem = (ImageView) spotGallery
							.getChildAt(i);
					if (i == index) {
						galleryItem
								.setBackgroundResource(R.drawable.page_indicator_sel);
					} else {
						galleryItem
								.setBackgroundResource(R.drawable.page_indicator_no);
					}

				}
				currentPage = index;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	public void toNextPage() {
		currentPage++;
		viewPaper.setCurrentItem(currentPage, true);
	}

	public void toPreviousPage() {
		currentPage--;
		viewPaper.setCurrentItem(currentPage, true);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}

	public int getRandomPersonHeadRes() {
		TypedArray headRes = getResources().obtainTypedArray(
				R.array.person_heads);
		int res = headRes.getResourceId(
				(int) (Math.random() * headRes.length()), 0);
		headRes.recycle();
		return res;
	}
}
